<?php
declare (strict_types=1);

namespace app\common\tool\Refund\Driver;

use app\common\model\Logs;
use app\common\tool\Refund\Exception\RefundException;
use think\facade\Log;
use WeChat\Contracts\Tools;

class WeChat
{
    public static function create($param, $trade_type)
    {
        $route = 'logs/weChatRefund.log';
        try{
            $config = $param->config[$param->merchantType][$trade_type];

            // 创建接口实例
            $wechat = new \WePay\Refund($config);
            // 组装参数，可以参考官方商户文档
            $options = [
                'appid'         => $config['appid'],
                'mch_id'        => $config['mch_id'],
                'out_trade_no'  => $param->out_trade_no,
                'out_refund_no' => $param->out_refund_no,
                'refund_fee'    => $param->refund_fee,
                'total_fee'     => $param->total_fee,
                'notify_url'    => $param->notify_url,
                'nonce_str'     => Tools::createNoncestr(),
            ];
            $sign = wechatSign($options);
            $options['sign'] = $sign;

            Logs::write($route, "微信退款单号:{$param->out_refund_no}退款执行参数：".json_encode($options,JSON_UNESCAPED_UNICODE));
            $result = $wechat->create($options);
            Logs::write($route, "微信退款单号:{$param->out_refund_no}退款同步响应结果：".json_encode($result,JSON_UNESCAPED_UNICODE));
            //{"return_code":"SUCCESS","return_msg":"OK","appid":"wx39455bd06b42e114","mch_id":"1641032166","nonce_str":"oM7S5LwUx5h6z5Ck","sign":"B426BFEAB5A06268E8E83441172926D14D3DD58F38253042696B3A5C4ADF796E","result_code":"SUCCESS","transaction_id":"4200001779202304202968773162","out_trade_no":"2023042031681962370","out_refund_no":"workRecord_202304201147018","refund_id":"50302605482023042033505534380","refund_channel":[],"refund_fee":"1","coupon_refund_fee":"0","total_fee":"1","cash_fee":"1","coupon_refund_count":"0","cash_refund_fee":"1"}

            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return ['code'=>1, 'msg'=>'退款成功', 'result'=>$result];
            }else{
                return ['code'=>-1, 'msg'=>'退款失败'];
            }

        }catch(\Throwable $t){
            $errMsg = [
                'desc'=>'退款异常',
                'errMessage'=>$t->getMessage(),
                'errFile'=>$t->getFile(),
                'errLine'=>$t->getLine()
            ];
            Logs::write($route, json_encode($errMsg,JSON_UNESCAPED_UNICODE));
            return ['code'=>-1, 'msg'=>'退款异常'];
        }
    }

}